<template>
  <div>
    <textarea :id="id" ref="ckeditorRef"></textarea>
  </div>
</template>

<script>
export default {
  name: "ckeditor4",
  props: {
    value: '',
    ckeditorHeight: {
      default: 450
    }
  },
  watch: {
    // 监听prop的变化，更新ckeditor中的值
    value() {
      if (this.value !== this.ckeditor.getData()) {
        console.log(this.value)
        this.ckeditor.setData(this.value)
      }
    }
  },
  data() {
    return {
      id: parseInt(Math.random() * 10000).toString(),
      ckeditor: null
    }
  },
  mounted() {
    window.CKEDITOR_BASEPATH = '/ckeditor/'
    import('ckeditor/ckeditor.js').then(comp => {
      const self = this
      let imgUrl = '/compilation/compilation/uploadImage'
      //渲染编辑器
      self.ckeditor = CKEDITOR.replace(self.id, {
        height: this.ckeditorHeight,
        // resize_enabled: false,
        toolbar : [
          { name: 'document', items: [ 'Source', '-', 'Save', 'NewPage', 'ExportPdf', 'Preview', 'Print', '-', 'Templates' ] },
          { name: 'clipboard', items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
          { name: 'editing', items: [ 'Find', 'Replace', '-', 'SelectAll', '-', 'Scayt' ] },
          { name: 'forms', items: [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField' ] },
          '/',
          { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat' ] },
          { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language' ] },
          { name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
          { name: 'insert', items: [ 'Image', 'Flash', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe' ] },
          '/',
          { name: 'styles', items: [ 'Styles', 'Format', 'Font', 'FontSize' ] },
          { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
          { name: 'tools', items: [ 'Maximize', 'ShowBlocks' ] },
          { name: 'about', items: [ 'About' ] }
        ],
        // removeButtons: 'Underline,Subscript,Superscript,Anchor,Link,Unlink,Maximize,Source,About',
        // removeDialogTabs: 'image:advanced;link:advanced',
        // filebrowserImageUploadUrl: imgUrl,
        // filebrowserUploadUrl: imgUrl,
        // extraPlugins: 'uploadimage,preview',
        // uploadUrl: imgUrl
      })

      // 设置初始内容
      self.ckeditor.setData(self.value)

      // 监听内容变更事件
      self.ckeditor.on("change", function() {
        self.$emit("input", self.ckeditor.getData())
      })

      self.ckeditor.on("instanceReady", function(evt) {
        self.$emit("ready", evt,CKEDITOR)
      })
    })
  },
  // 销毁组件前，销毁编辑器
  beforeDestroy() {
    // self.ckeditor.destroy()
  }
};
</script>